package cn.codeforfun.vote;

import cn.codeforfun.consts.SessionConsts;
import cn.codeforfun.prize.Prize;
import cn.codeforfun.prize.PrizeService;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * Created by Administrator on 2017/2/15 0015.
 */
@Controller
@RequestMapping("/vote")
public class VoteController {
    @Autowired
    private VoteService voteService;
    @Autowired
    private PrizeService prizeService;

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public List<Vote> list() {
        List<Vote> voteList = voteService.findAll();
        return voteList;
    }

    @RequestMapping("/save")
    @ResponseBody
    public boolean save(@RequestBody Vote vote) {
        System.out.println(vote);
        boolean flag = voteService.save(vote);
        return flag;
    }

    @RequestMapping("/detail/{id}")
    @ResponseBody
    public Vote detail(@PathVariable Long id) {
        return voteService.findOne(id);
    }

    @RequestMapping("/getPrizes")
    @ResponseBody
    public Map getPrizes(Long voteId) {
        Map map = new HashMap();
        List<Prize> prizes = prizeService.findAll();
        map.put("prizes", prizes);
        map.put("vote", voteService.findOne(voteId));
        return map;
    }


    @RequestMapping("/getQrcodeUrl/{id}")
    @ResponseBody
    public Map getQrcodeUrl(@PathVariable Long id) throws WxErrorException {
        String qrcodeUrl = voteService.getQrcodeUrl(id);
        Map map = new HashMap();
        map.put("url", qrcodeUrl);
        return map;
    }

    @RequestMapping("/surveyParam")
    @ResponseBody
    public Map surveyParam(HttpSession session) {
        Map map = new HashMap();
        map.put("vote", voteService.findOne(Long.valueOf(String.valueOf(session.getAttribute(SessionConsts.VOTE_ID)))));
        return map;
    }

    @RequestMapping("/vote")
    @ResponseBody
    public void vote(@RequestBody Vote vote, HttpSession session) throws WxErrorException {
        Set<Option> options = new LinkedHashSet<>();
        for (Question question : vote.getQuestions()) {
            question.setVote(vote);
            for (Option option : question.getOptions()) {
                option.setQuestion(question);
                if (option.getSelect()) {
                    options.add(option);
                }
                if ("radio".equals(question.getType()) && question.getSelect().toString().equals(option.getId().toString())) {
                    options.add(option);
                }
            }
        }
        voteService.vote(options, session);
    }
}
